package cn.com.java.controller;

import cn.com.java.annotation.SystemLog;
import cn.com.java.core.HttpRes;
import cn.com.java.core.ResponseEntity;
import cn.com.java.model.SysUser;
import cn.com.java.service.SysUserRoleService;
import cn.com.java.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;



@RestController
@RequestMapping("SysUser")
@RequiredArgsConstructor
@Slf4j
public class SysUserController {


    private final SysUserService sysUserService;

    private final SysUserRoleService sysUserRoleService;

    /**
     * 查询所有记录
     *
     * @return 返回集合，没有返回空List
     */
    @RequestMapping("list")
    public List<SysUser> listAll() {
        return sysUserService.list();
    }

    @GetMapping("listByPage")
    public HttpRes listByPage(int pageNum, int pageSize, String name) {
        Page<SysUser> page = new Page<>(pageNum, pageSize);

        QueryWrapper<SysUser> sysRoleQueryWrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            sysRoleQueryWrapper.like("name", name);
        }

        List<SysUser> sysUsers = sysUserService.getPageAndRole(page, sysRoleQueryWrapper);
        page.setRecords(sysUsers);
        return HttpRes.OK("查询成功", page);
    }


    /**
     * 根据主键查询
     *
     * @param id 主键
     * @return 返回记录，没有返回null
     */
    @RequestMapping("getById")
    public SysUser getById(Long id) {
        return sysUserService.getById(id);
    }

    /**
     * 新增，忽略null字段
     *
     * @param sysUser 新增的记录
     * @return 返回影响行数
     */

    @SystemLog("添加用户")
    @RequestMapping("insert")
    public HttpRes insert(@RequestBody SysUser sysUser) {
        sysUserService.save(sysUser);
        sysUserRoleService.saveBySysUser(sysUser);
        return HttpRes.OK("添加成功", sysUser);
    }

    /**
     * 修改，忽略null字段
     *
     * @param sysUser 修改的记录
     * @return 返回影响行数
     */
    @RequestMapping("update")
    @SystemLog("添加用户")
    public HttpRes update(@RequestBody SysUser sysUser) {
        sysUserService.updateById(sysUser);
        sysUserRoleService.updateBySysUser(sysUser);
        return HttpRes.OK("修改成功", sysUser);
    }

    /**
     * 删除记录
     *
     * @param id 待删除的记录
     * @return 返回影响行数
     */
    @RequestMapping("delete")
    public HttpRes delete(Long id) {
        return HttpRes.OK("删除成功", sysUserService.removeById(id));
    }

    @PostMapping("/login")
    @SystemLog("用户登录")
    public HttpRes login(@RequestBody SysUser sysUser) {
        log.info("用户名：[{}]", sysUser.getUserName());
        log.info("密码：[{}]", sysUser.getPassword());
        return sysUserService.login(sysUser);
    }


}